#ifndef __kraw_ResourceManager_h__
#define __kraw_ResourceManager_h__

#include <string>
#include <list>
#include <map>

#define resourcemgr ResourceManager::getInstance()

namespace kraw
{
	class AssetLoader;
	class Resource;
	class ResourceManager
	{
	public:
		static void init();

		static ResourceManager* getInstance();

		template<typename T>
		T* load(AssetLoader* loader, bool backgroundLoad = true)
		{
			T* resource = find<T>(loader);
			if (resource) {
				resource->retain();
				delete loader;
				return resource;
			}

			resource = new T(loader);
			if (resource) {
				if (backgroundLoad) {
					loadingList.push_back(resource);
				}
				else {
					if (loader->load()) // async step
						if (resource->load()) // sync step
							resourceMap[loader->getAssetName()] = resource;

					return resource;
				}
			}

			return NULL;
		}

		template<typename T>
		T* find(AssetLoader* loader)
		{
			T* resource = NULL;

			std::map<std::string, Resource*>::iterator itmap = resourceMap.find(loader->getAssetName());
			if (itmap != resourceMap.end()) {
				resource = dynamic_cast<T*>(itmap->second);
				return resource;
			}
			else {
				std::string assetName = loader->getAssetName();
				std::list<Resource*>::iterator itload;
				for (itload = loadingList.begin(); itload != loadingList.end(); ++itload)
				{
					if ((*itload)->getName() == assetName)
					{
						resource = dynamic_cast<T*>(*itload);
						return resource;
					}
				}

				//TODO- check currently loading
			}

			return NULL;
		}

	private:
		static ResourceManager* instance;

		std::list<Resource*> loadingList;
		std::map<std::string, Resource*> resourceMap;
	};
}

#endif
